<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
	<title>公共账本</title>
	<link rel="stylesheet" href="//cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.css">
	<link rel="stylesheet" href="//cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap-theme.css">
	<style>
		#operate-result-account span,
		#operate-result-group span{
			color: red;
			font-size: 12px;
			font-weight: 700;
		}
	</style>
</head>

<body ng-app="main">
<div id="main" class="container" ng-controller="MainCtrl">
	<div class="row">
		
	</div>
	<div class="row">
		<div class="col-xs-12 col-md-6">
			<div class="form-group">
				<label for="">搜索：</label>
				<input type="text" class="form-control" ng-model="search" />
			</div>
			<table class="table table-hover table-striped">
				<thead>
					<tr>
						<th>id</th>
						<th>项目</th>
						<th>金额</th>
						<th>组</th>
						<th>时间</th>
					</tr>
				</thead>
				<tbody>
					<tr ng-repeat="item in records | filter : search | limitTo : 10 : start">
						<td ng-bind="item.pk"></td>
						<td ng-bind="item.fields.name"></td>
						<td ng-bind="item.fields.price"></td>
						<td ng-bind="item.fields.group"></td>
						<td ng-bind="item.fields.time | date : 'yyyy-MM-dd'"></td>
					</tr>
				</tbody>
			</table>
			<div>共 <span ng-bind="pageNumber"></span> 页</div>
			<ul class="pagination">
				<li><a href="javascript:;">首页</a></li>
				<li ng-repeat="i in pages" ng-click="toPage(i*10)"><a href="javascript:;" ng-bind="i+1"></a></li>
				<li><a href="javascript:;">尾页</a></li>
			</ul>
		</div>
		<div class="col-xs-12 col-md-6">
			<div class="row">
				<div class="col-xs-12 col-md-6">
					<form id="form-add-group" >
						<div class="form-group">
						    <label>组名称</label>
						    <input type="text" name="name" class="form-control" />
						</div>
						<div class="form-group">
						    <label>项目名称</label>
						    <input type="text" name="item" class="form-control" />
						</div>
						<input type="button" ng-click="post()" class="form-control btn btn-info" value="添加组">
					</form>
				</div>
				<div class="col-xs-12 col-md-6">
					<div class="panel panel-primary">
						<div class="panel-heading">操作结果</div>
						<div class="panel-body" id="operate-result-group"></div>
					</div>
				</div>
			</div>
			
			<hr>
			<div class="row">
				<div class="col-xs-12 col-md-6">
					<form id="form-add-account" >
						<div class="form-group">
						    <label>选择项目：<span ng-bind="itemName | json"></span></label>
						    <!-- m.id as m.productName for m in model -->
						    <select ng-model="itemName" ng-options="m as m.item group by m.name for m in groups" class="form-control">
							</select>
						</div>
						<div class="from-group">
							<label for="price">金额</label>
							<input class="form-control" type="number" name="price" id="price" >
						</div>
						<br>
						<input type="button" ng-click="postAccount()" class="form-control btn btn-info" value="记账">
					</form>
				</div>
				<div class="col-xs-12 col-md-6">
					<div class="panel panel-primary">
						<div class="panel-heading">操作结果</div>
						<div class="panel-body" id="operate-result-account"></div>
					</div>
				</div>
			</div>
			
		</div>
	</div>
	<hr>
	<div id="counts">
		花费总和：<span style="color:red;font-size : 30px;font-weight: 700;" ng-bind="sum | number"></span>
		<br>
		郭雅定需要交的钱：<span style="color: blue;font-size: 30px; text-decoration: underline;" ng-bind="gyd | number"></span>		
		<br>
		其余人平均花费：<span style="color:red;font-size : 30px;font-weight: 700;" ng-bind="others | number"></span>
	</div>
</div>
<hr>
<div class="container">
	
	<div id="highchart"></div>
</div>
<script type="text/javascript" src="//cdn.bootcss.com/jquery/1.11.1/jquery.js"></script>
<script type="text/javascript" src="//cdn.bootcss.com/angular.js/1.5.8/angular.js"></script>
<script type="text/javascript" src="http://cdn.hcharts.cn/highcharts/highcharts.js"></script>
<script type="text/javascript" src="http://cdn.hcharts.cn/highcharts/modules/drilldown.js"></script>

<script type="text/javascript">
app = angular.module('main', [])
// function get_result(r) {
// 	arr = []
// 	angular.froEach(r, function (i,item) {
// 		arr.push(item.fields)
// 	})
// }
app.controller('MainCtrl', ['$scope','$http', function (scope,http) {
	accountData(scope);
	function accountData(scope) {
		http.get('/list/Account/').success(function (result) {
			scope.records = result
			scope.pageNumber = Math.ceil(result.length / 10)
			scope.pages = []
			for( i = 0 ;i < scope.pageNumber;i++ ){
				scope.pages.push(i)
			}
			calculate(result);
			// count 统计数据
			scope.gyd = 0;
			scope.sum = 0;
			scope.others = 0;
			angular.forEach(result, function (item,i) {
				if ( item.fields.group != '食材' ){

					scope.gyd += parseInt(item.fields.price)
				}
				else{
					scope.others += parseInt(item.fields.price)
				}
				scope.sum += parseInt( item.fields.price )
			})
			scope.gyd /= 6
			scope.others /= 5
			scope.others += scope.gyd
		})
	}
	// 组级联表单
	groupData(scope);
	function groupData(scope) {
		$.getJSON('/list/Group/').done(function (result) {
			// console.log(result)
			scope.groups = []
			scope.groupMap = {}
			scope.items  = []


			angular.forEach(result, function (item,i) {
				var groupName = item.fields['name'];
				var itemName = item.fields['item'];

				scope.groups.push(item.fields);
				if( !scope.groupMap[ groupName ] ){
					scope.groupMap[ groupName ] = [];
				}

				scope.groupMap[ groupName ].push( itemName );
			})

			scope.itemName = scope.groups[1]
		})
	}

	// 表格分页
	scope.records = []
	scope.start = 0
	scope.toPage = function (num) {
		scope.start = num
	}
	// 提交添加组
	scope.post = function () {
		formData = {}
		$('#form-add-group [name]').each(function (i,item) {
			formData[ item.name ] = item.value
		})

		$.ajax({
			url  : '/add/Group/',
			method : 'POST',
			data : formData
		})
		.done(function (resp) {
			console.log(resp)
			$('#operate-result-group').append( '添加组成功：<span>'+formData.name+ ' : ' + formData.item + '</span><br />' )
			groupData(scope)
		})
	}
	// 提交添加记账
	scope.postAccount = function () {
		postData = {
			name : scope.itemName.item,
			time : new Date().getTime(),
			price : $('#price').val(),
			group : scope.itemName.name,
		}

		$.ajax({
			url : '/add/Account/',
			method : 'POST',
			data  :postData
		})
		.done(function (resp) {
			console.log(resp)
			$('#operate-result-account').append( '添加记账成功：<span>'+postData.name+':'+postData.price+'</span><br />' )
			accountData(scope)
		})

	}
}])

function calculate(result) {
	brandsData = []
	drilldownSeries = []

	var brandsDataCells = {}
	var drilldownSeriesCells = {}
	angular.forEach(result, function (item, i) {
		
		group = item.fields.group
		if( !brandsDataCells[ group ] ){
			brandsDataCells[ group ] = {
				"name": group,
				"y": 0,
				"drilldown": group
			};
			drilldownSeriesCells[ group ] = {
				"name": group,
				"id": group,
				"data": []
			}
		}
		name  = item.fields.name;
		price = item.fields.price;
		time  = item.fields.time;
		
		var datacell = [ name , price ];
		drilldownSeriesCells[ group ][ "data" ].push( datacell );
		brandsDataCells[ group ][ "y" ] += price;
		
	})
	for( key in brandsDataCells ){
		brandsData.push( brandsDataCells[key] )
	}

	for( key in drilldownSeriesCells ){
		drilldownSeries.push( drilldownSeriesCells[key] )
	}
	console.log( '-----------------' )
	console.log(drilldownSeries)
	show_chart(brandsData ,drilldownSeries)
}

// highchart
function show_chart(brandsData ,drilldownSeries) {

    // Create the chart
    $('#highchart').highcharts({
        chart: {
        	// 柱形图
            type: 'bar'
        },
        title: {
            text: '统计数据'
        },
        subtitle: {
            text: '点击查看详细'
        },
        xAxis: {
            type: 'category',
            title: {
            	text: '组'
            }
        },
        yAxis: {
            title: {
                text: '金额'
            }
        },
        legend: {
            enabled: false
        },
        plotOptions: {
            series: {
                borderWidth: 2,
                dataLabels: {
                    enabled: true,
                    format: '{point.y:.1f}'
                }
            }
        },
        tooltip: {
            headerFormat: '<span style="font-size:11px">{series.name}</span><br>',
            pointFormat: '<span style="color:{point.color}">{point.name}</span>: <b>{point.y:.2f}</b><br/>'
        },
        series: [{
            name: '组',
            colorByPoint: true,
            data: brandsData
        }],
        drilldown: {
            series: drilldownSeries
        }
    });
}

</script>
</body>
</html>